package com.aifeng.hassan_food.mine

import android.annotation.SuppressLint
import android.os.Bundle
import android.view.View
import android.widget.LinearLayout
import android.widget.TextView
import androidx.recyclerview.widget.SimpleItemAnimator
import com.aifeng.base.*
import com.aifeng.common_ui.base.find
import com.aifeng.common_ui.base.gone
import com.aifeng.common_ui.base.visible
import com.aifeng.common_ui.helper.dp2px
import com.aifeng.common_ui.helper.getString
import com.aifeng.common_ui.helper.toNotInt
import com.aifeng.hassan_food.R
import com.aifeng.model.CommonData
import com.aifeng.utils.bindLifeCycle
import com.aifeng.utils.onTabSelectedListener
import com.aifeng.utils.subscribeByNoError
import com.aifeng.viewmodel.OrderViewModel
import com.sunfusheng.GlideImageView
import kotlinx.android.synthetic.main.activity_share.*
import kotlinx.android.synthetic.main.layout_empty.*
import kotlinx.android.synthetic.main.layout_list.*
import net.idik.lib.slimadapter.SlimAdapter
import org.koin.androidx.viewmodel.ext.android.getViewModel

class ShareActivity : BaseActivity() {

    private var mIndex: Int = 0
    private var mInviteNum: Int = 0
    private var mMonthNum: Int = 0
    private var mTotalNum: Int = 0
    private var mState = ""

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_share)
        initTitle(title = "我的邀请")
    }

    override fun getViewModel() = getViewModel<OrderViewModel>()

    override fun initTitle(title: String, name: String, divider: Boolean) {
        super.initTitle(title, name, divider)
        mIndex = intent.getIntExtra("index", 0)
        initTabLayout()
        initList()

        empty_img.apply {
            layoutParams = LinearLayout.LayoutParams(
                dp2px(80f),
                dp2px(80f)
            ).apply {
                setMargins(0, dp2px(50f), 0, 0)
            }
        }
    }

    private fun initTabLayout() {
        share_tab.apply {
            onTabSelectedListener {
                onTabSelected {
                    mState = if (it!!.position == 0) "1" else "0"

                    getViewModel().cancelRequest()
                    getViewModel().delay { updateList() }
                }
            }
            addTab(
                newTab().apply {
                    setCustomView(R.layout.item_share_tab)
                    customView?.find<TextView>(R.id.item_tab_num)?.gone()
                    customView?.find<TextView>(R.id.item_tab_title)?.text = "已确认"
                },
                mIndex == 0
            )
            addTab(
                newTab().apply {
                    setCustomView(R.layout.item_share_tab)
                    customView?.find<TextView>(R.id.item_tab_num)?.gone()
                    customView?.find<TextView>(R.id.item_tab_title)?.text = "待确认"
                },
                mIndex == 1
            )
        }
    }

    @SuppressLint("SetTextI18n")
    private fun initList() {
        empty_hint.text = "暂无相关邀请信息！"
        swipe_refresh.refresh { getData() }
        recycle_list.apply {
            (itemAnimator as SimpleItemAnimator).supportsChangeAnimations = false //去除闪烁
            loadLinear(baseContext, swipe_refresh)

            mAdapter = SlimAdapter.create()
                .register<CommonData>(R.layout.item_share_list) { data, injector ->

                    val index = mList.indexOf(data)

                    injector.text(R.id.item_share_name, data.nick)
                        .text(R.id.item_share_tel, data.phone)
                        .with<GlideImageView>(R.id.item_share_img) {
                            it.loadCircleImage(data.headimg)
                        }
                        .visibility(
                            R.id.item_share_agree,
                            if (mState == "1") View.GONE else View.VISIBLE
                        )
                        .clicked(R.id.item_share_agree) {
                            getViewModel().inviteAgree(data.id)
                                .bindLifeCycle(getLifecycleOwner())
                                .subscribeByNoError(
                                    event = getViewModel(),
                                    onSuccess = {
                                        mList.removeAt(index)
                                        mAdapter.notifyItemRemoved(index)
                                        empty_view.apply { if (mList.isEmpty()) visible() else gone() }

                                        if (mInviteNum > 0) updateTab(mInviteNum - 1)
                                        mTotalNum++
                                        mMonthNum++
                                        share_total.text = mTotalNum.toString()
                                        share_add.text = "本月新增 $mMonthNum 人"
                                    }
                                )
                        }
                }
                .attachTo(this)
        }
    }

    @SuppressLint("SetTextI18n")
    override fun getData(index: Int, isLoading: Boolean) {
        getViewModel().inviteList(
            state = mState,
            userId = getString("userId"),
            onSuccess = {

                //解构声明
                val (
                    month,
                    total,
                    state,
                    list
                ) = it

                mList.clear()
                mList.addItems(list)
                mAdapter.updateData(mList)

                mInviteNum = state.toNotInt()
                mTotalNum = total.toNotInt()
                mMonthNum = month.toNotInt()

                share_total.text = total
                share_add.text = "本月新增 $month 人"
                updateTab(mInviteNum)
            },
            onFinally = {
                swipe_refresh.isRefreshing = false
                empty_view.apply { if (mList.isEmpty()) visible() else gone() }
            }
        )
    }

    private fun updateList() {
        swipe_refresh.isRefreshing = true

        empty_view.gone()
        if (mList.isNotEmpty()) {
            mList.clear()
            mAdapter.notifyDataSetChanged()
        }

        getData()
    }

    private fun updateTab(num: Int) {
        share_tab.getTabAt(1)?.let { tab ->
            val itemView = tab.customView?.find<TextView>(R.id.item_tab_num)
            itemView?.let {
                it.visibility = if (num > 0) View.VISIBLE else View.GONE
                it.text = num.toString()
            }
        }
    }

}
